const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const cookieSession = require('cookie-session');
const consolidate = require('consolidate');
const flash = require('connect-flash');

const server = express();
server.use(bodyParser.urlencoded({extended:false}));
server.use(cookieParser());
server.use(cookieSession({
    keys:['111','2222','3333','4444','555']
}));
server.use(flash());

server.use(function(req,res,next){
    //res.locals 属性是express模板引擎最后分配的数据对象，因为每个模板都要分配user数据，所以直接写入这个对象即可
    res.locals.user = req.session.user;
    res.locals.success = req.flash('success').toString();
    res.locals.error = req.flash('error').toString();
    //路由信息
    next();
});

server.set('view engine','html');

server.set('views','./views');

server.engine('html',consolidate.ejs);

//静态文件设置 有顺序，必须放在路由的上面
server.use(express.static(__dirname+'/public'));

//路由
let index = require('./router/index');
let login = require('./router/login');

server.use('/index',index);
server.use('/login',login);
server.use('/article',require('./router/article'));
server.use('/api',require('./router/api'));

server.use((req,res,next)=>{
    let err = new Error('Not Found');
    err.status = 404;
    next(err);
})
server.use((err,req,res,next)=>{
    res.locals.message = err.message;
    res.locals.status = err.status;
    res.render('err.ejs');
})

server.listen(8888);
